package com.hwg.emp.service.impl;

import com.hwg.emp.common.service.CommonService;
import com.hwg.emp.common.util.DBUtil;
import com.hwg.emp.dao.DaoFactory;
import com.hwg.emp.dao.UserDAO;
import com.hwg.emp.model.UserMD;
import com.hwg.emp.service.UserService;

public class UserServiceImpl extends CommonService implements UserService {

	private UserDAO dao = DaoFactory.getDao(UserDAO.class);
	
	@Override
	public UserMD login(String account, String password) throws Exception {
		//验证参数
		//断言不为空，如果为空则抛出异常信息为"账户不能为空"
		account = $("账户不能为空", account);
		//断言不为空，如果为空则抛出异常信息为"密码不能为空"
		password = $("密码不能为空", password);
		// 2业务逻辑判断
		UserMD user = dao.select("account", account);
		//断言不为null，如果为空则抛出异常信息为"账户不存在"
		assertNotNull("账户不存在", user);
		//断言结果为true，如果不为true则抛出异常信息为"账户和密码不匹配"
		assertTrue("账户和密码不匹配", user.getPassword().equals(password));
		
		return user;
	}
    
	/**
	 * 修改密码的服务
	 */
	@Override
	public void updatePassword(UserMD t) throws Exception {
		// TODO Auto-generated method stub
		DBUtil.beginTranscation();
		int i = dao.update(t);
		if (i>0) {
			DBUtil.commitTranscation();
		}else {
			DBUtil.rollbackTranscation();
		}
	}
    
	/**
	 * 增加用户的服务
	 */
	@Override
	public void insertUser(UserMD t) throws Exception {
		// TODO Auto-generated method stub
		DBUtil.beginTranscation();
		int i = dao.insert(t);
		if (i>0) {
			DBUtil.commitTranscation();
		}else {
			DBUtil.rollbackTranscation();
		}
	}

	@Override
	public UserMD queryUserById(String id) throws Exception {
		UserMD user = dao.select("id", id);
		return user;
	}

	@Override
	public UserMD queryUserByAccount(String account) throws Exception {
		UserMD user = dao.select("account", account);
		return user;
	}

	@Override
	public boolean deleteUsersByIds(String... ids) throws Exception {
		// TODO Auto-generated method stub
		DBUtil.beginTranscation();
		int count = 0;
		for (String id : ids) {
				count += dao.delete("id", id);
		}
		if(count==ids.length){
			DBUtil.commitTranscation();
			return true;
		}else{
			DBUtil.rollbackTranscation();
			return false;
		}
	}

	@Override
	public void updateUserOnfo(UserMD t) throws Exception {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
				DBUtil.beginTranscation();
				int i = dao.update(t);
				if (i>0) {
					DBUtil.commitTranscation();
				}else {
					DBUtil.rollbackTranscation();
				}
	}

	@Override
	public UserMD select(String uk, String ukValue) throws Exception {
		// TODO Auto-generated method stub
		return dao.select(uk, ukValue);
	}
   
}
